<template>
	<view class="qr-code">
		<view class="qr-code-banner">
			<view class="panel">
				<view class="panel-group">
					<view class="panel-item">
						二维码ID：<text class="panel-item-body">{{qrcodeId}}</text>
					</view>
					<view class="panel-item">
						设备类型：<text class="panel-item-body">{{qrcodeType}}</text>
					</view>
					<view class="panel-item">
						二维码状态：<text class="panel-item-body">{{qrcodeactivate}}</text>
					</view>
					<view class="panel-item">
						街景采集：<text class="panel-item-body"></text>
					</view>

					<view class="list">
						<view class="list-group" v-if="!isimages">
							<view class="list-item" v-for="(item, index) in imagesArr" :key="index">
								<view class="card">
									<view class="card-header">
									</view>
									<view class="delete" @click="deleteImg(index)">
										<image class="icon" mode="aspectFit"
											src="@/static/icon_b1ogyrvee2o/delete-icon.png"></image>
									</view>
									<view class="card-body" @click="showImage(index, imagesArr)">
										<image class="icon" mode="aspectFit"
											:src="'http://www.qjjxh.com:8081/file/'+ item"></image>
									</view>
								</view>
							</view>
							<view class="list-item" v-if="imagesArr.length < 3">
								<view class="card upload" @click="takePictures">
									<view class="card-body">
										<image class="icon" src="@/static/icon_b1ogyrvee2o/camera-icon.png"></image>
									</view>
								</view>
							</view>
						</view>

						<view class="list-group" v-else>
							<view class="list-item" v-for="(item, index) in modeimagesArr" :key="index">
								<view class="card">
									<view class="card-body" @click="showImage(index, modeimagesArr)">
										<image class="icon" mode="aspectFit"
											:src="'http://www.qjjxh.com:8081/file/'+ item"></image>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<view class="map-wrap">
			<view class="panel">
				<view class="panel-group">
					<view class="panel-item uni-common-pl">
						地图定位：<text class="panel-item-body">{{poiNameData}}</text>
					</view>
				</view>
			</view>

			<map class="map" id="map" ref="map" :longitude="longitude" :latitude="latitude" :scale="scale"
				:markers="markers" :circles="circles" show-location="show-location" @markertap="markertap">
				<view class="btns btns-b">
					<view class="btn-item">
						<cover-image class="icon" @click="getMyLocation"
							src="@/static/icon_b1ogyrvee2o/scopes-icon.png"></cover-image>
					</view>
				</view>
				<view class="btns btns-a" v-if="isithidden">
					<view class="btns-group" v-if="!isRelated">
						<cover-view class="ch-btn ch-btn-b" :class="{'disable': activate === '0'}" @click="getInstall">
							设备关联</cover-view>
						<cover-view class="ch-btn ch-btn-a" :class="{'disable': activate === '1'}" @click="getActivate">
							激活</cover-view>
					</view>
					<view class="btns-group" v-else>
						<cover-view class="ch-btn ch-btn-b" @click="getHangUp">挂起</cover-view>
						<cover-view class="ch-btn ch-btn-a" @click="getSubmit">提交</cover-view>
					</view>
				</view>

				<view class="tips">
					<cover-view class="tips-bg"></cover-view>
					<view class="tips-body">
						<view class="tips-item">
							<cover-image class="tips-item-header" src="@/static/city-manage/marker-blue.png">
							</cover-image>
							<cover-view class="tips-item-body">绑定二维码设备</cover-view>
						</view>
						<view class="tips-item">
							<cover-image class="tips-item-header" src="@/static/city-manage/marker-grey.png">
							</cover-image>
							<cover-view class="tips-item-body">未绑定设备</cover-view>
						</view>
						<view class="tips-item">
							<cover-image class="tips-item-header" src="@/static/city-manage/marker-yellow.png">
							</cover-image>
							<cover-view class="tips-item-body">已绑定设备</cover-view>
						</view>
						<view class="tips-item">
							<cover-image class="tips-item-header" src="@/static/city-manage/marker-red.png">
							</cover-image>
							<cover-view class="tips-item-body">移动端设备</cover-view>
						</view>
					</view>
				</view>
			</map>
		</view>
	</view>
</template>

<script>
	import {
		submitQRcode,
		getqrCode,
		getqrcodeunbind,
		getqrcodeisbind
	} from '@/api/my_task.js'; //激活
	import URL from '@/util/url.js'
	export default {
		data() {
			return {
				userInfo: uni.getStorageSync('userInfo'),
				GDMap: null,
				marker: null,
				//H5
				longitude: '',
				latitude: '',
				covers: [],

				bindqrcodes: [], //已绑定二维码id

				qrcodeIddata: [],
				scale: 12, //缩放级别
				markers: [], //标记点
				circles: [], //圆

				isbindimages: '',
				modeimagesArr: [], // 后台返回的
				imagesArr: [], //调相机拍照的照片
				images: [], //提交的
				poiNameData: '',
				qrcodeId: '', //二维码ID
				qrcodeType: '', //设备类型
				qrcodeactivate: '', //二维码状态
				equipmenttypeid:'',//设备类型id
				activate: '',

				searchForm: {
					id: '',
					isActivate: '1',
					address: '',
					qrcodeGeometry: '',
					images: '',
				},
				unbinddata: [],
				equipmentId: '', //设备id
				equipmentType: '', //设备类型
				isRelated: false,
				isithidden: true,
				isimages: false,
				isBindIds: [], //绑定时存储的数据
			}
		},
		onLoad(options) {
			//用户登录信息
			this.userInfo = uni.getStorageSync('userInfo');
			const token = uni.getStorageSync('token');


			this.getqrCode(options.id);

			this.qrcodeId = options.id
			this.searchForm.id = this.qrcodeId

			//初始化地图
			this._initMap();

			//激活
			uni.$on('test', () => {
				this.test()
			})
			//监听绑定 、unbind
			uni.$on('bindID', ({
				id
			}) => {
				this.updateMarker(id, 'bind')
			});
			//监听取消绑定 、unbind
			uni.$on('unbindID', ({
				id
			}) => {
				this.updateMarker(id, 'unbind')
			});
			//监听unbind子窗体关闭
			uni.$on('closeunbind', () => {
				let subNVue = uni.getSubNVueById('unbind')
				subNVue.hide('fade-out', 300)
			});
			//监听concat子窗体关闭
			uni.$on('closeframe', () => {
				let subNVue = uni.getSubNVueById('concat')
				subNVue.hide('fade-out', 300)
			});
			// 监听isbind子窗体关闭
			uni.$on('closeisbind', () => {
				let subNVue = uni.getSubNVueById('isbind')
				subNVue.hide('fade-out', 300)

			});
			//监听hangup子窗体关闭
			uni.$on('closehangup', () => {
				let subNVue = uni.getSubNVueById('hangup')
				subNVue.hide('fade-out', 300)
			});
			//监听submit子窗体关闭
			uni.$on('closesubmit', () => {
				let subNVue = uni.getSubNVueById('submit')
				subNVue.hide('fade-out', 300)
			});
			//监听submint弹出提交成功框
			uni.$on('submittip', () => {
				this.$tip.toast('提交成功', () => {
					setTimeout(() => {
						uni.reLaunch({
							url: "/pages/home"
						})
					}, 1000);
				})
			});
			//监听hangup弹出挂起成功框
			uni.$on('hanguptip', () => {
				this.$tip.toast('挂起成功', () => {
					setTimeout(() => {
						uni.reLaunch({
							url: "/pages/home"
						})
					}, 1000);
				})
			});
			uni.$on('hanguptiplong', () => {
				this.$tip.toast('请填写备注', () => {})
			})

		},
		//得到map对象
		onReady() {
			this.map = uni.createMapContext("map", this);
		},
		onUnload() {
			// 移除监听事件
			uni.$off('test');
			uni.$off('bindID');
			uni.$off('unbindID');
			uni.$off('closeunbind');
			uni.$off('closeframe');
			uni.$off('closeisbind');
			uni.$off('closehangup');
			uni.$off('closesubmit');
			uni.$off('submittip');
			uni.$off('hanguptip');
			uni.$off('hanguptiplong');
		},
		methods: {
			//判断点位是否有id 、标记点变黄
			updateMarker(id, type) {
				//绑定->图标变黄
				if (type == 'bind') {
					if (!this.isBindIds.includes(id)) {
						this.equipmentId = id
						this.isBindIds.push(id);
						let isBindMarker = this.markers.find((item) => item.id == id);
						isBindMarker.iconPath = '../../static/city-manage/marker-yellow.png';
						//取消绑定删除isBindIds中的数据
						this.markers = this.markers.slice(0);
					}
				} else {
					//取消绑定->图标变灰
					if (this.isBindIds.includes(id)) {
						this.equipmentId = ''
						//已绑定点位判断是否有id、
						let index = this.isBindIds.findIndex((item) => item == id);
						this.isBindIds.splice(index, 1);
						let isBindMarker = this.markers.find((item) => item.id == id);
						//如果有这个id，为蓝色点位，没有为灰色点位
						if (this.qrcodeIddata.includes(id)) {
							isBindMarker.iconPath = '../../static/city-manage/marker-blue.png';
						} else {
							isBindMarker.iconPath = '../../static/city-manage/marker-grey.png';
						}
						this.markers = this.markers.slice(0);
					}
				}
			},
			//挂起按钮----->hangup
			getHangUp() {
				uni.$emit('qrcodeID', {
					qrcodeId: this.qrcodeId,
				})
				//打开弹框子窗体
				const subNVue = uni.getSubNVueById('hangup')
				subNVue.setStyle({
					"position": "absolute",
					// "width": "340px",
					"height": "200px",
					"left": "20px",
					"right": "20px",
					"top": "300px",
					"background": "transparent",
				});
				subNVue.show('fade-in', 300, function() {
				})
			},
			//提交按钮---------->submit
			getSubmit() {
				//打开弹框子窗体
				const subNVue = uni.getSubNVueById('submit')
				subNVue.setStyle({
					"position": "absolute",
					"height": "135px",
					"left": "50px",
					"right": "50px",
					"top": "300px",
					"background": "transparent",
				});
				uni.$emit('submitData', {
					qrcodeId: this.qrcodeId,
					equipmentId: this.equipmentId,
					equipmentType: this.equipmenttypeid,
				})
				subNVue.show('fade-in', 300, function() {
				})
			},
			//设备关联
			getInstall() {
				//判断关联按钮是否可以点击
				if (this.activate === '0') {
					return;
				}
				//点击显示挂起/提交
				this.isRelated = true;
			},
			//激活
			getActivate() {
				//判断激活按钮是否可以点击
				if (this.activate === '1') {
					return;
				}
				//提交图片
				this.searchForm.images = this.imagesArr.join(",")
				//判断是否有图片
				if (this.searchForm.images === '') {
					this.$tip.toast('请添加图片');
					return;
				}
				//定位经纬拼接
				this.searchForm.qrcodeGeometry = "POINT(" + this.longitude + " " + this.latitude + ")"

				//打开弹框子窗体 frame
				const subNVue = uni.getSubNVueById('concat')
				subNVue.setStyle({
					"position": "absolute",
					// "width": "300px",
					"height": "135px",
					"left": "50px",
					"right": "50px",
					"top": "300px",
					"background": "transparent",
				});
				subNVue.show('fade-in', 300, function() {
				})
			},

			//map移动至中点
			getMyLocation() {
				this.map.moveToLocation({
					latitude: this.latitude,
					longitude: this.longitude,
					success(res) {}
				});
			},
			//初始化地图
			_initMap() {
				let _this = this;
				// #ifdef APP-PLUS
				uni.getLocation({
					type: 'gcj02',
					geocode: true,
					success: function(res) {
						//定位地址
						_this.poiNameData = res.address.poiName;
						//激活时提交的地址
						_this.searchForm.address = _this.poiNameData
						//定位经纬
						_this.latitude = res.latitude;
						_this.longitude = res.longitude;
						// 点标记
						let market = {
							latitude: _this.latitude,
							longitude: _this.longitude,
							iconPath: '../../static/city-manage/marker-red.png',
						}
						// 圆范围
						let circles = {
							latitude: _this.latitude,
							longitude: _this.longitude,
							fillColor: "#e6060a6A", //填充的颜色
							color: "#e6060a6A", //描边的颜色
							radius: 1500, //半径
							strokeWidth: 2, //描边的宽度
						}
						_this.markers.push(market);
						/* _this.markers[0] = market;
						_this.markers = [..._this.markers]; */
						_this.circles[0] = circles;
						_this.circles = [..._this.circles];

					},
					fail: function(err) {
					},
				});
				// #endif

				// #ifdef H5
				this.latitude = '34.230564';
				this.longitude = '108.938192';
				// 点标记
				let market = {
					id: 1,
					latitude: this.latitude,
					longitude: this.longitude,
					iconPath: '../../static/city-manage/marker-red.png',
				}
				// 圆范围
				let circles = {
					latitude: _this.latitude,
					longitude: _this.longitude,
					fillColor: "#e6060a6A", //填充的颜色
					color: "#e6060a6A", //描边的颜色
					radius: 200, //半径
					strokeWidth: 2, //描边的宽度
				}
				_this.markers[0] = market;
				_this.markers = [..._this.markers];
				_this.circles[0] = circles;
				_this.circles = [..._this.circles];

				// #endif
			},



			//获取接口信息
			getqrCode(id) {
				let _this = this
				getqrCode(id).then((res) => {
					_this.equipmenttypeid = res.data.equipmenttypeid
					_this.qrcodeType = res.data.equipmenttype
					_this.qrcodeactivate = res.data.is_activate
					_this.activate = res.data.is_activate;

					if (res.data.is_activate === '0') {
						_this.qrcodeactivate = '未激活'
					} else if (res.data.is_activate === '1') {
						_this.qrcodeactivate = '激活'
						_this.isimages = true;
					}
					if (res.data.status === '2') {
						_this.$tip.toast('该二维码正在审核', () => {
							setTimeout(() => {
								uni.reLaunch({
									url: "/pages/home"
								})
							}, 2000);
						})
					} else if (res.data.status === '3') {
						_this.isithidden = false;
						_this.isimages = true;
						_this.$tip.toast('该二维码审核通过', () => {

						})
					} else if (res.data.status === '4') {
						_this.$tip.toast('该二维码正在挂起', () => {
							setTimeout(() => {
								uni.reLaunch({
									url: "/pages/home"
								})
							}, 2000);
						})
					} else {

					}
					//返回的图片
					if (res.data.images) {
						if (res.data.images.indexOf(',')) {
							let urls = res.data.images.split(',');
							_this.modeimagesArr = [...urls]
						} else {
							_this.modeimagesArr.push(res.data.images)
						}
					}
					//查询未绑定二维码的设备
					_this.getqrcodeunbind(res.data.equipmenttypeid)
					//查询已绑定二维码的设备
					_this.getqrcodeisbind(res.data.equipmenttypeid)



				})
			},

			//查询未绑定二维码的设备
			getqrcodeunbind(data) {
				let _this = this
				getqrcodeunbind(data).then((res) => {
					if (res.data.length == 0) {
						return;
					}
					let data = res.data
					data.forEach((mapdata, index) => {
						if (JSON.parse(mapdata.gcjGeometry)) {
							let gcjGeometry = JSON.parse(mapdata.gcjGeometry).coordinates;
							let market = {
								id: mapdata.id,
								latitude: gcjGeometry[1],
								longitude: gcjGeometry[0],
								iconPath: '../../static/city-manage/marker-grey.png',
							}
							_this.markers.push(market)
						}

					})
				})
			},

			//查询已绑定二维码的设备
			getqrcodeisbind(data) {
				let _this = this
				getqrcodeisbind(data).then((res) => {
					if (res.data.length == 0) {
						return;
					}
					let data = res.data;
					_this.bindqrcodes = data.slice(0);
					data.forEach((mapdata, index) => {
						if (JSON.parse(mapdata.gcjGeometry)) {
							let gcjGeometry = JSON.parse(mapdata.gcjGeometry).coordinates;
							let market = {
								qrcodeId: mapdata.qrCodeId,
								id: mapdata.id,
								latitude: gcjGeometry[1],
								longitude: gcjGeometry[0],
								iconPath: '../../static/city-manage/marker-blue.png',
							}
							_this.markers.push(market)
							//数据先存在数组中，判断点击点位数组中有没有
							if (!_this.qrcodeIddata) {
								_this.qrcodeIddata = []
							}
							_this.qrcodeIddata.push(market.id)
						}
					})
				})
			},

			//点击地图上的点位
			markertap(e) {
				if (this.activate == '1') {
					//选中已绑定的点
					let markerId = e.detail.markerId;
					this.equipmentId = markerId
					//已绑定中存在的ID
					let isFind = this.qrcodeIddata.find(item => markerId == item)
					if (isFind) {
						//打开弹框子窗体
						let subNVue = uni.getSubNVueById('isbind')
						subNVue.setStyle({
							"position": "absolute",
							"width": "100%",
							"height": "520px",
							"bottom": "0px",
							"background": "transparent",
						});
						//存储在数组中的数据(unbind)
						let curItem = this.bindqrcodes.find(item => markerId == item.id)
						//定义一个isBinding判断是否是 绑定/取消绑定
						let isBinding = (this.isBindIds.includes(markerId));

						if (!isBinding && this.isBindIds.length > 0) {
							return;
						}
						let qrcodeId = curItem.qrCodeId;
						this.isbindimages = curItem.images;
						uni.$emit('isbindID', {
							isBinding: isBinding,
							qrcodeId: this.qrcodeId,
							oldqrcopdeId: qrcodeId,
							equipmentId: e.target.markerId,
							equipmentType: this.equipmenttypeid,
							poiNameData: this.poiNameData,
							images: this.isbindimages,
						})
						subNVue.show('fade-in', 300, function() {})
					} else {
						//未绑定中的点
						//打开弹框子窗体
						let subNVue = uni.getSubNVueById('unbind')
						subNVue.setStyle({
							"position": "absolute",
							"width": "100%",
							"height": "310px",
							"bottom": "0px",
							"background": "transparent",
						});

						let isBinding = (this.isBindIds.includes(markerId));

						if (!isBinding && this.isBindIds.length > 0) {
							return;
						}

						uni.$emit('sendID', {
							isBinding: isBinding,
							poiNameData: this.poiNameData,
							equipmentId: e.target.markerId,
							qrcodeId: this.qrcodeId,
							equipmentType: this.equipmenttypeid
						})

						subNVue.show('fade-in', 300, function() {

						})
					}
				} else {
					this.$tip.toast('请先激活二维码！', () => {})
				}
			},
			//调手机相册或相机
			takePictures() {
				let _this = this;

				// 选择图片
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['camera'],
					success: function(res) {
						uni.showLoading({
							title: '正在上传'
						})
						//提交图片
						const tempFilePaths = res.tempFilePaths;
						const uploadTask = uni.uploadFile({
							url: URL.Upload,
							filePath: tempFilePaths[0],
							name: 'file',
							formData: {
								'user': 'test'
							},
							success: function(uploadFileRes) {
								let res = JSON.parse(uploadFileRes.data);
								if (res.code === 200) {
									_this.imagesArr.push(res.fileName)
									// console.info(_this.imagesArr)
									uni.hideLoading()
								}
							}
						})

					},
				});
			},

			//点击图片放大
			showImage(index, arr) {
				arr.forEach((key, index) => {
					key = 'http://www.qjjxh.com:8081/file/' + key
					arr[index] = key;
				})
				console.info(arr)
				let _this = this;
				uni.previewImage({
					urls: arr,
					current: index,
					longPressActions: {
						//itemList: ['发送给朋友', '保存图片', '收藏'],//按钮的文字数组
						success: function(data) {
						},
						fail: function(err) {
						}
					}
				});
			},

			// 删除本地图片：未上传
			deleteImg(index) {
				this.imagesArr.splice(index, 1);
			},

			//提交激活
			test() {
				let searchFormData = this.searchForm
				submitQRcode(searchFormData).then((res) => {
					if (res.code === 200) {
						this.activate = '1';
						this.qrcodeactivate = '激活';
						this.$tip.toast('激活成功', () => {

						})
					} else {}
				}).catch((err) => {
				});
			}

		}
	}
</script>

<style lang="scss">
	.list {
		height: 143rpx;

		.list-group {
			display: flex;
			justify-content: center;

			.list-item {
				width: 33.33%;
			}
		}
	}

	.card {
		width: 223rpx;
		margin: 0rpx auto;
		border-radius: 5rpx;
		border: 1rpx solid #a2a2a2;
		position: relative;
		top: 0rpx;
		left: 0rpx;

		.card-body {
			height: 143rpx;

			.icon {
				width: 100%;
				height: 100%;
			}
		}

		&.upload {
			border: none;
		}

		.card-header {
			width: 100%;
			height: 31rpx;
			position: absolute;
			top: 0rpx;
			left: 0rpx;
			background-color: #000000;
			opacity: 0.3;
			z-index: 2;
		}

		.delete {
			width: 31rpx;
			height: 31rpx;
			position: absolute;
			top: 0rpx;
			right: 0rpx;
			z-index: 3;
			display: flex;
			justify-content: center;
			align-items: center;

			.icon {
				width: 20rpx;
				height: 20rpx;
			}
		}

	}

	.panel {
		.panel-group {
			.panel-item {
				margin-bottom: 10rpx;
				font-size: 32rpx;
				line-height: 40rpx;
				color: #777777;

				.panel-item-body {
					color: #333333;
				}
			}
		}
	}

	.qr-code {
		position: absolute;
		top: 0rpx;
		right: 0rpx;
		bottom: 0rpx;
		left: 0rpx;

		.qr-code-banner {
			padding: 20rpx 30rpx 18rpx;
			background-color: #ffffff;
		}

		.map-wrap {
			margin-top: 400rpx;
			padding: 20rpx 0rpx 0rpx 0rpx;
			position: absolute;
			top: 0rpx;
			right: 0rpx;
			bottom: 0rpx;
			left: 0rpx;
			background-color: #ffffff;

			.map {
				margin-top: 74rpx;
				width: auto;
				height: auto;
				position: absolute;
				top: 0rpx;
				right: 0rpx;
				bottom: 0rpx;
				left: 0rpx;
			}

		}
	}

	.btns-a {
		position: absolute;
		right: 0rpx;
		bottom: 32rpx;
		left: 0rpx;
		display: flex;
		justify-content: center;

		.btns-group {
			display: flex;
			justify-content: center;

			.ch-btn {
				width: 270rpx;
				height: 94rpx;
				margin: 0rpx 25rpx;
				padding: 24rpx 0rpx 26rpx;
				font-size: 36rpx;
				line-height: 44rpx;
				text-align: center;
				border-radius: 47rpx;

				&.ch-btn-b {
					color: #333333;
					background-color: #ffffff;
				}

				&.ch-btn-a {
					color: #ffffff;
					background-color: #c4534c;
				}

				&.disable {
					color: #ffffff;
					background-color: #aaaaaa;
				}
			}

		}

	}

	.btns-b {
		position: absolute;
		top: 124rpx;
		right: 22rpx;

		.btn-item {
			width: 92rpx;
			height: 92rpx;
		}

		.icon {
			width: 92rpx;
			height: 92rpx;
		}
	}



	.tips {
		width: 240rpx;
		height: 220rpx;
		position: absolute;
		bottom: 200rpx;
		left: 0rpx;

		.tips-bg {
			width: 240rpx;
			height: 200rpx;
			position: absolute;
			bottom: 0rpx;
			right: 0rpx;
			background-color: #ffffff;
			border-radius: 20rpx;
			overflow: hidden;
		}

		.tips-body {
			position: absolute;
			top: 0rpx;
			right: 0rpx;
			bottom: 0rpx;
			left: 0rpx;
			padding: 20rpx;

			.tips-item {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.tips-item-header {
					width: 50rpx;
					height: 50rpx;
				}

				.tips-item-body {
					width: 210rpx;
					font-size: 24rpx;
					color: #777777;
					line-height: 30rpx;
					height: 30rpx;
				}
			}
		}
	}
</style>
